import requests
import json
import cv2
import base64
from PIL import Image, ImageDraw
from datetime import datetime

# import paddlehub as hub

open_file = "./img/gp.jpg"
img = Image.open(open_file)


def cv2_to_base64(image):
    data = cv2.imencode('.jpg', image)[1]
    return base64.b64encode(data.tostring()).decode('utf8')


def drawPic(left, bottom, right, top):
    # Image1 = Image.open("./img/1.png")
    draw = ImageDraw.Draw(img)
    # left bottom right top
    draw.rectangle((left, bottom, right, top), None, 'red')
    # img.show()
    # img.save("test.png")


def save(save_file):
    img.show()
    img.save(save_file)


if __name__ == '__main__':
    # 发送HTTP请求
    data = {'images': [cv2_to_base64(cv2.imread(open_file))]}
    headers = {"Content-type": "application/json"}
    url = "http://49.235.95.23:9292/predict/ultra_light_fast_generic_face_detector_1mb_640"
    r = requests.post(url=url, headers=headers, data=json.dumps(data))
    print('data:' + json.dumps(data))
    # 打印预测结果
    res = r.json()["results"]
    print(res)

    # writeFile(str(date.today().strftime("%Y-%m-%d-%H-%M-%S")) + '.json', r.json()["results"])
    json_name = "./json/" + str(datetime.now().strftime("%Y-%m-%d-%H-%M-%S"))
    with open(json_name + '.json', 'w', encoding='utf-8') as json_file:
        json.dump(r.json()["results"], json_file, ensure_ascii=False)
        print("write json file success!")

    #  获取框边
    tmp = json.loads(json.dumps(res[0]))
    print(tmp)
    for i in tmp['data']:
        left = i['left']
        bottom = i['bottom']
        right = i['right']
        top = i['top']
        drawPic(left, bottom, right, top)
    save("./img/res1.png")
